package com.csust.automaticteach.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csust.automaticteach.annotation.AuthCheck;
import com.csust.automaticteach.common.BaseResponse;
import com.csust.automaticteach.common.ResultUtils;
import com.csust.automaticteach.exception.BusinessException;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.exception.ThrowUtils;
import com.csust.automaticteach.manager.auth.SpaceUserAuthManager;
import com.csust.automaticteach.model.dto.space.SpaceAddRequest;
import com.csust.automaticteach.model.dto.space.SpaceEditRequest;
import com.csust.automaticteach.model.dto.space.SpaceQueryRequest;
import com.csust.automaticteach.model.dto.space.SpaceUpdateRequest;
import com.csust.automaticteach.model.entity.Space;
import com.csust.automaticteach.model.entity.User;
import com.csust.automaticteach.model.enums.SpaceLevelEnum;
import com.csust.automaticteach.model.vo.space.SpaceLevel;
import com.csust.automaticteach.model.vo.space.SpaceVO;
import com.csust.automaticteach.service.SpaceService;
import com.csust.automaticteach.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.csust.automaticteach.constant.UserAuthConstant.ADMIN_ROLE;

/**
 * ClassName SpaceController
 *
 * @Description 空间控制器
 * @Author 钰玟
 * @Date 2025/8/13 下午3:32
 * Version 1.0
 **/
@RestController
@RequestMapping("/space")
public class SpaceController {
    @Resource
    private SpaceService spaceService;
    @Resource
    private UserService userService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 添加空间
     *
     * @param spaceAddRequest 添加空间请求
     * @param request         请求
     * @return 响应
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(spaceId);
    }

    /**
     * 更新空间 -- 管理员使用
     *
     * @param spaceUpdateRequest 更新空间请求
     * @return 响应
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space, false);
        // 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 编辑空间 -- 用户使用
     *
     * @param spaceEditRequest 编辑空间请求
     * @return 响应
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 判断是否存在
        long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        //判断权限 是否可以修改
        if (!oldSpace.getUserId().equals(userService.getLoginUser(request).getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 查询空间列表 -- 管理员使用
     *
     * @param spaceQueryRequest 查询空间请求
     * @return 响应
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        //1.校验参数
        ThrowUtils.throwIf(spaceQueryRequest == null, ErrorCode.PARAMS_ERROR);
        //2.分页查询字段
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        //3.分页查询实体类
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize), spaceService.getQueryWrapper(spaceQueryRequest));
        //4.返回
        return ResultUtils.success(spacePage);
    }
    /**
     * 查询空间vo列表 -- 管理员使用
     *
     * @param spaceQueryRequest 查询空间请求
     * @return 响应
     */
    @PostMapping("/list/vo/page")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        //1.校验参数
        ThrowUtils.throwIf(spaceQueryRequest == null, ErrorCode.PARAMS_ERROR);
        //2.分页查询字段
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        //3.分页查询实体类
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize), spaceService.getQueryWrapper(spaceQueryRequest));
        List<Space> records = spacePage.getRecords();
        //4.转换为VO page对象
        List<SpaceVO> spaceVOList = records.stream().map(SpaceVO::objToVo).toList();
        Page<SpaceVO> spaceVOPage = new Page<>(current, pageSize, spacePage.getTotal());
        spaceVOPage.setRecords(spaceVOList);
        //5.返回
        return ResultUtils.success(spaceVOPage);
    }
    /**
     * 根据id查询空间详情
     *
     * @param id 空间id
     * @return 响应
     */
    @PostMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(@RequestParam("id") Long id,HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        //1.校验参数
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        //2.查询空间 ,转化为vo对象
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        //3.获取权限列表
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        //3.并且返回
        return ResultUtils.success(spaceVO);
    }

    /**
     * 获取空间级别列表
     * @return 响应
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

}
